package com.jjc.android.activity

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import androidx.viewpager.widget.ViewPager.OnPageChangeListener
import com.jjc.android.GlobalManager
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.adapter.SimpleFragmentPagerAdapter
import com.jjc.android.base.BaseActivity
import com.jjc.android.fragment.ScreenSlideFragment
import com.jjc.android.util.MultiLanguageUtil
import com.jjc.android.view.FlowTransformer
import com.tbuonomo.viewpagerdotsindicator.DotsIndicator
import kotlin.math.abs

class GuideActivity : BaseActivity(){

    companion object{
        fun start(context: Context){
            val intent = Intent(context, GuideActivity::class.java)
            context.startActivity(intent)
        }
    }

    override val layoutId: Int = R.layout.activity_guide
    private lateinit var dotsIndicator: DotsIndicator
    private lateinit var pager: ViewPager
    private var mPreviousPositionOffset = 0f
    private var mViewPagerScrollingLeft = false
    private var mPreviousPosition = 0
    private lateinit var pagerAdapter: PagerAdapter
    private val gestureDetector by lazy {
        GestureDetector(this, object : SimpleOnGestureListener(){
            override fun onFling(
                e1: MotionEvent,
                e2: MotionEvent,
                velocityX: Float,
                velocityY: Float
            ): Boolean {
                if (currentItem == guideTotalLength-1) {
                    if (abs(e1.x - e2.x) > Math.abs(e1.y - e2.y)
                        && (e1.x - e2.x <= -flaggingWidth || e1.x - e2.x >= flaggingWidth)
                    ) {
                        if (e1.x - e2.x >= flaggingWidth) {
                            endTutorial()
                            return true
                        }
                    }
                }
                return false
            }
        })
    }
    private var guideTotalLength = 3
    override fun initView(savedInstanceState: Bundle?) {
        initViews()
        val fragments = (if(MultiLanguageUtil.getInstance().isEnglish) GlobalManager.guideImagesEn else GlobalManager.guideImages).let { images->
            if(images.isNullOrEmpty()){
                guideTotalLength = 3
                (0 until 3).map { ScreenSlideFragment.newInstance(it,null,it==2) }
            }else{
                guideTotalLength = images.size
                images.mapIndexed { index, s -> ScreenSlideFragment.newInstance(index,s,index==images.size-1) }
            }
        }
        pagerAdapter = SimpleFragmentPagerAdapter(supportFragmentManager,fragments)
        pager.offscreenPageLimit = 4
        pager.adapter = pagerAdapter
        pager.setPageTransformer(true, FlowTransformer())
        pager.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                if (positionOffset > mPreviousPositionOffset && position == mPreviousPosition || positionOffset < mPreviousPositionOffset && position > mPreviousPosition) {
                    mViewPagerScrollingLeft = true
                } else if (positionOffset < mPreviousPositionOffset) {
                    mViewPagerScrollingLeft = false
                }
                mPreviousPositionOffset = positionOffset
                mPreviousPosition = position

                // FADE the indicator layout
                if (position == 1 && mViewPagerScrollingLeft) {
                    dotsIndicator.alpha = 1 - positionOffset
                } else if (position == 1 && !mViewPagerScrollingLeft) {
                    dotsIndicator.alpha = 1 - positionOffset
                }
            }

            override fun onPageSelected(position: Int) {
                currentItem = position
                if (position == guideTotalLength-1) {
                    dotsIndicator.visibility = View.GONE
                } else {
                    dotsIndicator.visibility = View.VISIBLE
                }
            }

            override fun onPageScrollStateChanged(state: Int) {}
        })
        dotsIndicator.setViewPager(pager)
    }


    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (gestureDetector.onTouchEvent(event)) {
            event.action = MotionEvent.ACTION_CANCEL
        }
        return super.dispatchTouchEvent(event)
    }
    private var currentItem = 0
    private var flaggingWidth = 0

    override fun onDestroy() {
        super.onDestroy()
        pager.clearOnPageChangeListeners()
    }

    fun endTutorial() {
        UserManager.isShowGuide = true
        if(!UserManager.toLogin(this)){
            MainActivity.start(this)
        }
        finish()
    }

    override fun onBackPressed() {
        if (pager.currentItem == 0) {
            super.onBackPressed()
        } else {
            pager.currentItem = pager.currentItem - 1
        }
    }

    private fun initViews() {
        pager = findViewById(R.id.pager)
        dotsIndicator = findViewById(R.id.dots_indicator)
    }
}